/*
    This file is part of FSJController.

    FSJController is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    FSJController is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with FSJController.  If not, see <http://www.gnu.org/licenses/>.
*/

package de.qsc.fsjcontroller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class FSAppCallChain extends FSBuildingBlock {

    static Logger logger = LoggerFactory.getLogger(FSAppCallChain.class);

    private int step = 0;
    String[][] fsAppCmds;
    FSBuildingBlock finalBuildingBlock;

    public FSAppCallChain(FSChannel channel, FSBuildingBlock finalBuildingBlock, String[]... args) {
        super(channel);
        this.finalBuildingBlock = finalBuildingBlock;
        fsAppCmds = args;
    }

    public void setFinalBuildingBlock(FSBuildingBlock finalBuildingBlock) {
        this.finalBuildingBlock = finalBuildingBlock;
    }

    @Override
    public void handleEvent(FSEvent event) throws Exception {
        if (event.getName().equals(FSEvent.Name.CHANNEL_PARK) || event.getName().equals(FSEvent.Name.CHANNEL_EXECUTE_COMPLETE)) {
            if (hasNext()) {
                next();
            } else if (finalBuildingBlock != null) {
                activateNextBuildingBlock(finalBuildingBlock);
            }
        }
    }

    public void onFailure() {
        logger.error("failure");
    }

    public void start() {
        if (hasNext()) {
            next();
        }
    }

    public void update(String[][] args) {
        step = 0;
        this.fsAppCmds = args;
    }

    public boolean hasNext() {
        return fsAppCmds.length > step;
    }

    public void next() {
        if (fsAppCmds[step].length > 0 && !fsAppCmds[step][0].isEmpty()) {
            runApplication(fsAppCmds[step][0], fsAppCmds[step][1]);
        }
        step++;
    }
}
